using System;
using System.Collections.Generic;
using DataStubGenerator.Controls;

namespace Lib.Controls
{
    public class GetHighlightsCommand
    {
        public IEnumerable<string> Keywords
        {
            get { return _keywords; }
        }

        public List<Highlight> Highlights
        {
            get { return _highlights; }
        }

        private readonly SqlModel _model;
        private readonly IEnumerable<string> _keywords;
        private readonly List<Highlight> _highlights;

        public GetHighlightsCommand(SqlModel model, IEnumerable<string> keywords)
        {
            if (model == null)
                throw new ArgumentNullException("model",
                                                "GetHighlightsCommand::ctor(): model reference can not be null!");
            _model = model;
            _keywords = (keywords==null ? 
                            new List<string>() : 
                            keywords) ;
            _highlights = new List<Highlight>();
        }


        public void Execute()
        {
            int totalCharsUpToThisLine = 0;

            foreach (string line in _model.Sql) {
                MarkHighlights(line.ToLower(), totalCharsUpToThisLine);

                totalCharsUpToThisLine += line.Length;
            }
        }

        void MarkHighlights(string line, int totalCharsUpToThisLine) {
            foreach (string keyword in _keywords)
                AppendLineHighlights(line, keyword, totalCharsUpToThisLine);
        }

        void AppendLineHighlights(string line, string keyword, int ttlCharsUpToTHisLine)
        {
            int lastFoundIndex;
            int searchAt = 0;

            while (searchAt < line.Length &&
                    (lastFoundIndex = line.IndexOf(keyword, searchAt)) != -1) {
                _highlights.Add(
                    new Highlight(lastFoundIndex + searchAt + ttlCharsUpToTHisLine, keyword.Length,
                                  _model.GetHighlightColor(keyword)));
                searchAt += lastFoundIndex + keyword.Length;
            }
        }
    }
}
